
#include <iostream>

#include "../UniPrint/print.h"
#include "BTree.h"
#include "_share/rand.h"
using namespace std;
/**
 * @brief 生成随机数据，随机insert、search、remove测试BTree
 *
 * @tparam T 可以是所有类型，本实现是支持实现move的key的
 * @param order 是B树的度数
 * @param n 是B树中最多能拥有的结点数量
 */
template <typename T>
void testBTree(int order, int n)
{
    // int fd = open("input", O_RDWR|S_IRUSR);
    BTree<T> bt(order);
    while (bt.size() < n) {
        T e = T(dice(n * 3));  //[0, 3n)范围内的e
        int t = dice(3);
        // std::string tt = std::to_string(t) + " " + std::to_string(e) + "\n";
        // write(fd,tt.data(),tt.size());
        // fut << t << ' ';
        switch (t) {
            case 0: {  //查找，成功率 <= 33.3%
                printf("Searching for ");
                print(e);
                printf(" ... ");
                typename BTree<T>::BTNodePosi p = bt.search(e);
                printf(p ? "Found\n" : "Not found\n");
                break;
            }
            case 2: {  //删除，成功率 <= 33.3%
                printf("Removing ");
                print(e);
                printf(" ... ");
                if (bt.remove(e))
                    printf("Done\n"), print(bt);
                else
                    printf("Not exists\n");
                break;
            }
            default: {  //插入，成功率 == 100%
                printf("Inserting ");
                print(e);
                printf(" ... ");
                int oldSize = bt.size();
                if (bt.insert(e))
                    printf("Done\n"), print(bt);
                else
                    printf("Dup key\n");
                break;
            }
        }
    }
    // return;
    // 将剩下的元素删除
    while (bt.size() > 0) {
        T e = dice((T)n * 3);  //[0, 3n)范围内的e
        printf("Removing ");
        print(e);
        printf(" ... ");
        if (bt.remove(e))
            printf("Done\n"), print(bt);
        else
            printf("Not exists\n");
    }
}

/******************************************************************************************
 * 测试主入口
 ******************************************************************************************/
int main(int argc, char* argv[])
{
    setbuf(stdout, nullptr);
    if (3 > argc) {
        printf("Usage: %s <order of B-tree> <size of test>\a\a\n", argv[0]);
        return 1;
    }
    int order = atoi(argv[1]);
    if (order < 3) {
        printf("Make sure the order (%d) is no less than 3.\a\a\n", order);
        return 1;
    }
    int size = atoi(argv[2]);
    if (size < 0) {
        printf("Make sure the size (%d) is no less than 0.\a\a\n", size);
        return 1;
    }
    srand((unsigned int)time(NULL));               // 设置随机种子
    testBTree<int>(atoi(argv[1]), atoi(argv[2]));  //元素类型、比较器可以在这里任意选择
    return 0;
}